package Threads.CAS;


import java.text.DateFormat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;


//使用cas可以实现一个锁
public class CAS_LOCK {
    private static AtomicInteger state=new AtomicInteger(0);

    public static void lock(){
        while (true){
            if (state.compareAndSet(0,1))
                break;
        }
    }

    public static void unlock(){
        state.set(0);
    }

    //测试自己实现的锁
    public static void main(String[] args) {
        Thread t1=new Thread(()->{

                lock();
                System.out.println("t1 -----running");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t1 Done!");
                unlock();

        });
        Thread t2=new Thread(()->{

                lock();
                System.out.println("t2------running");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                 System.out.println("t2 Done!");
                unlock();

        });

        t1.start();
        t2.start();
    }
}
